"""
自定义标题栏组件 - 完全融入软件主题的标题栏
"""

from PySide2.QtWidgets import (QWidget, QHBoxLayout, QLabel, QPushButton, 
                              QVBoxLayout, QFrame, QSizePolicy)
from PySide2.QtCore import Qt, QPoint, Signal
from PySide2.QtGui import QFont, QIcon, QPixmap, QPainter, QLinearGradient, QColor
import os


class CustomTitleBar(QWidget):
    """自定义标题栏"""
    
    # 信号
    minimize_clicked = Signal()
    maximize_clicked = Signal()
    close_clicked = Signal()
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent_window = parent
        self.is_dark_mode = True
        self.drag_position = None
        self.is_maximized = False
        
        self.setFixedHeight(40)
        self.setup_ui()
        
    def setup_ui(self):
        """设置UI"""
        layout = QHBoxLayout(self)
        layout.setContentsMargins(10, 0, 5, 0)
        layout.setSpacing(0)
        
        # 左侧：图标和标题
        left_layout = QHBoxLayout()
        left_layout.setSpacing(10)
        
        # 应用图标
        self.icon_label = QLabel()
        try:
            if os.path.exists("icon.ico"):
                icon_pixmap = QPixmap("icon.ico").scaled(24, 24, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                self.icon_label.setPixmap(icon_pixmap)
            else:
                self.icon_label.setText("🎬")
                self.icon_label.setFont(QFont("Segoe UI Emoji", 16))
        except:
            self.icon_label.setText("🎬")
            self.icon_label.setFont(QFont("Segoe UI Emoji", 16))
        
        self.icon_label.setFixedSize(24, 24)
        self.icon_label.setAlignment(Qt.AlignCenter)
        
        # 应用标题
        self.title_label = QLabel("解析器 v2.1")
        self.title_label.setFont(QFont("Microsoft YaHei UI", 10, QFont.Bold))
        
        left_layout.addWidget(self.icon_label)
        left_layout.addWidget(self.title_label)
        left_layout.addStretch()
        
        # 右侧：窗口控制按钮
        right_layout = QHBoxLayout()
        right_layout.setSpacing(0)
        
        # 最小化按钮
        self.minimize_btn = self.create_control_button("🗕", "最小化")
        self.minimize_btn.clicked.connect(self.on_minimize)
        
        # 最大化/还原按钮
        self.maximize_btn = self.create_control_button("🗖", "最大化")
        self.maximize_btn.clicked.connect(self.on_maximize)
        
        # 关闭按钮
        self.close_btn = self.create_control_button("🗙", "关闭", is_close=True)
        self.close_btn.clicked.connect(self.on_close)
        
        right_layout.addWidget(self.minimize_btn)
        right_layout.addWidget(self.maximize_btn)
        right_layout.addWidget(self.close_btn)
        
        # 添加到主布局
        layout.addLayout(left_layout)
        layout.addLayout(right_layout)
        
        # 应用样式
        self.update_theme(self.is_dark_mode)
        
    def create_control_button(self, text, tooltip, is_close=False):
        """创建控制按钮"""
        btn = QPushButton(text)
        btn.setFixedSize(45, 30)
        btn.setToolTip(tooltip)
        btn.setFont(QFont("Segoe UI Symbol", 10))
        
        if is_close:
            btn.setStyleSheet(self.get_close_button_style())
        else:
            btn.setStyleSheet(self.get_control_button_style())
            
        return btn
    
    def get_control_button_style(self):
        """获取控制按钮样式"""
        if self.is_dark_mode:
            return """
                QPushButton {
                    background: transparent;
                    border: none;
                    color: #6ca6fd;
                    border-radius: 4px;
                }
                QPushButton:hover {
                    background: rgba(255, 255, 255, 0.1);
                    color: #6ca6fd;
                }
                QPushButton:pressed {
                    background: rgba(255, 255, 255, 0.2);
                }
            """
        else:
            return """
                QPushButton {
                    background: transparent;
                    border: none;
                    color: rgba(0, 0, 0, 0.7);
                    border-radius: 4px;
                }
                QPushButton:hover {
                    background: rgba(0, 0, 0, 0.1);
                    color: #000000;
                }
                QPushButton:pressed {
                    background: rgba(0, 0, 0, 0.2);
                }
            """
    
    def get_close_button_style(self):
        """获取关闭按钮样式"""
        return """
            QPushButton {
                background: transparent;
                border: none;
                color: rgba(255, 255, 255, 0.8);
                border-radius: 4px;
            }
            QPushButton:hover {
                background: #e74c3c;
                color: #ffffff;
            }
            QPushButton:pressed {
                background: #c0392b;
            }
        """
    
    def update_theme(self, is_dark_mode):
        """更新主题"""
        self.is_dark_mode = is_dark_mode
        
        if is_dark_mode:
            # 夜间模式 - 深邃科技感
            self.setStyleSheet("""
                CustomTitleBar {
                    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                        stop:0 rgba(12, 12, 12, 0.95),
                        stop:0.3 rgba(26, 26, 46, 0.95),
                        stop:0.7 rgba(22, 33, 62, 0.95),
                        stop:1 rgba(15, 52, 96, 0.95));
                    border-bottom: 1px solid rgba(0, 212, 255, 0.3);
                }
            """)
            self.title_label.setStyleSheet("color: #6ca6fd; background: transparent;")
            self.icon_label.setStyleSheet("color: #00d4ff; background: transparent;")
        else:
            # 日间模式 - 纯蓝色（调暗）
            self.setStyleSheet("""
                CustomTitleBar {
                    background: rgba(0, 51, 102, 0.95);
                    border-bottom: 1px solid rgba(255, 255, 255, 0.3);
                }
            """)
            self.title_label.setStyleSheet("color: #ffffff; background: transparent;")
            self.icon_label.setStyleSheet("color: #ffffff; background: transparent;")
        
        # 更新按钮样式
        self.minimize_btn.setStyleSheet(self.get_control_button_style())
        self.maximize_btn.setStyleSheet(self.get_control_button_style())
        self.close_btn.setStyleSheet(self.get_close_button_style())
    
    def on_minimize(self):
        """最小化"""
        self.minimize_clicked.emit()
        if self.parent_window:
            self.parent_window.showMinimized()
    
    def on_maximize(self):
        """最大化/还原"""
        self.maximize_clicked.emit()
        if self.parent_window:
            if self.is_maximized:
                self.parent_window.showNormal()
                self.maximize_btn.setText("🗖")
                self.maximize_btn.setToolTip("最大化")
                self.is_maximized = False
            else:
                self.parent_window.showMaximized()
                self.maximize_btn.setText("🗗")
                self.maximize_btn.setToolTip("还原")
                self.is_maximized = True
    
    def on_close(self):
        """关闭"""
        self.close_clicked.emit()
        if self.parent_window:
            self.parent_window.close()
    
    def mousePressEvent(self, event):
        """鼠标按下事件 - 开始拖拽"""
        if event.button() == Qt.LeftButton:
            self.drag_position = event.globalPos() - self.parent_window.frameGeometry().topLeft()
            event.accept()
    
    def mouseMoveEvent(self, event):
        """鼠标移动事件 - 拖拽窗口"""
        if event.buttons() == Qt.LeftButton and self.drag_position and not self.is_maximized:
            self.parent_window.move(event.globalPos() - self.drag_position)
            event.accept()
    
    def mouseDoubleClickEvent(self, event):
        """双击事件 - 最大化/还原"""
        if event.button() == Qt.LeftButton:
            self.on_maximize()
            event.accept()
    
    def mouseReleaseEvent(self, event):
        """鼠标释放事件"""
        self.drag_position = None
